package org.xqyy.eval.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.xqyy.eval.exception.BusinessException;
import org.xqyy.eval.model.TUser;
import org.xqyy.eval.service.IUserService;
import org.xqyy.eval.util.ExceptionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by luoxiaoming on 16-12-26.
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;


    @RequestMapping("/loadUsers")
    public
    @ResponseBody
    Map<String, Object> loadUsers(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> res = new HashMap();
        List<Map<String, Object>> data = userService.load(res);
        res.put("root", data);
        return res;
    }

    /**
     * 查询所有用户
     * @return
     */
    @RequestMapping("/selectAllUser")
    @ResponseBody
    public List<TUser> selectAllUser(){
        return userService.selectAllUserAndTDept();
    }

    @RequestMapping("/loadSingleUser")
    public
    @ResponseBody
    Map<String, Object> loadSingleUser(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> res = new HashMap();
        Map<String, Object> user = (Map<String, Object>) request.getSession().getAttribute("user");//获取当前会话的session中的user
        res.put("deptCode", user.get("deptCode"));
        List<Map<String, Object>> data = userService.loadSingle(res);
        res.put("root", data);
        return res;
    }


    @RequestMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<>();
        try {
            String username = request.getParameter("username");
            String realName = request.getParameter("realName");
            String cell = request.getParameter("cell");
            String password = request.getParameter("password");
            String type = request.getParameter("type");
            String deptCode = request.getParameter("deptCode");
            String activeTime = request.getParameter("activeTime");
            String deadTime = request.getParameter("deadTime");
            res.put("username", username);
            res.put("realName", realName);
            res.put("cell", cell);
            res.put("password", password);
            res.put("type", type);
            res.put("deptCode", deptCode);
            res.put("activeTime", activeTime);
            res.put("deadTime", deadTime);
            res.put("status", true);
            userService.add(res);
            res.put("success", "操作成功!");
        } catch (Exception e) {
            res.put("failure", e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 新的用户添加功能
     * @param tUser
     * @return
     */
    @RequestMapping("/addTUser")
    @ResponseBody
    public Boolean addTUser(TUser tUser) {
        try {
            tUser.setPassword("qq");
            userService.addTUser(tUser);
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        }
    }

    /**
     * 新的用户修改功能
     * @param tUser
     * @return
     */
    @RequestMapping("/updateTUser")
    @ResponseBody
    public Boolean updateTUser(TUser tUser) {
        try {
            TUser tempuser = userService.findTUserById(tUser);
            tUser.setPassword(tempuser.getPassword());
            userService.updateTUser(tUser);
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        }
    }

    /**
     * 新的用户状态切换
     * @param tUser
     * @return
     */
    @RequestMapping("/changTUserStatus")
    @ResponseBody
    public Boolean changTUserStatus(TUser tUser) {
        try {
            userService.changTUserStatus(tUser);
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        }
    }

    /**
     * 查询一个用户
     * @return
     */
    @RequestMapping("/getTUserById")
    @ResponseBody
    public TUser getTUserById(TUser tUser) {
        return userService.findTUserById(tUser);
    }


    @RequestMapping("/updateUser")
    @ResponseBody
    public Map<String, Object> updateUser(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<>();
        try {
            String username = request.getParameter("username");
            String realName = request.getParameter("realName");
            String cell = request.getParameter("cell");
            String password = request.getParameter("password");
            String type = request.getParameter("type");
            String deptCode = request.getParameter("deptCode");
            String activeTime = request.getParameter("activeTime");
            String deadTime = request.getParameter("deadTime");
            String status = request.getParameter("status");
            res.put("username", username);
            if (StringUtils.hasLength(realName)) {
                res.put("realName", realName);
            }
            if (StringUtils.hasLength(cell)) {
                res.put("cell", cell);
            }
            if (StringUtils.hasLength(password)) {
                res.put("password", password);
            }
            if (StringUtils.hasLength(type)) {
                res.put("type", type);
            }
            if (StringUtils.hasLength(deptCode)) {
                res.put("deptCode", deptCode);
            }
            if (StringUtils.hasLength(activeTime)) {
                res.put("activeTime", activeTime);
            }
            if (StringUtils.hasLength(deadTime)) {
                res.put("deadTime", deadTime);
            }
            if (StringUtils.hasLength(realName)) {
                res.put("realName", realName);
            }
            if (StringUtils.hasLength(status)) {
                res.put("status", Boolean.valueOf(status));
            }
            userService.modify(res);
            res.put("success", "操作成功!");
        } catch (Exception e) {
            res.put("failure", e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    @RequestMapping("/deleteUser")
    @ResponseBody
    public Map<String, Object> deleteUser(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<>();
        try {
            String username = request.getParameter("username");
            res.put("username", username);
            userService.delete(res);
            res.put("success", "操作成功!");
        } catch (Exception e) {
            res.put("failure", e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 修改密码页面
     * @return
     */
    @RequestMapping("/alertPasswordPage")
    public ModelAndView alertPasswordPage(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("jsp/system/alertPassword");
        return modelAndView;
    }

    /**
     * 修改密码
     * @return
     */
    @RequestMapping("/alertPassword")
    @ResponseBody
    public Boolean alertPassword(TUser user){
        try {
            userService.alertPassword(user);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    /**
     * 新的系统用户登录控制器
     * @param user
     * @return
     */
    @RequestMapping("/userLogin")
    @ResponseBody
    public boolean userLogin(TUser user,HttpServletRequest request){
        if (userService.userLogin(user)){
            user = userService.findUserByUserNameAndPassword(user);
            request.getSession().setAttribute("user", user);
            log.info( "{}登录",user.getUsername());
            return true;
        }else {
            return false;
        }
    }

    @RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<>();
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            username=  username.toUpperCase();
            res.put("username", username);
            Map<String, Object> user = userService.loadOne(res);
            if (user == null || !user.get("password").equals(password)) {
                throw new RuntimeException("帐号或者密码不正确");
            } else {
                request.getSession().setAttribute("user", user);
            }
            res.put("type",user.get("type"));
            res.put("success", "登录成功!");
        } catch (Exception e) {
            res.put("failure", e.getMessage());
            e.printStackTrace();
        }
        return res;
    }



    @RequestMapping("/normalLogin")
    @ResponseBody
    public Map<String, Object> normalLogin(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<>();
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            username=  username.toUpperCase();
            res.put("username", username);
            Map<String, Object> user = userService.loadOne(res);
            if (user == null || !user.get("password").equals(password)) {
                res.put("success", "帐号或者密码不正确!");
                res.put("state", false);
            } else {
                request.getSession().setAttribute("user", user);
                res.put("success", "登录成功!");
                res.put("type", user.get("type"));
                res.put("state", true);
            }

        } catch (Exception e) {
            res.put("failure", e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    @RequestMapping("/loadCurrUserInfo")
    @ResponseBody
    public Map<String, Object> loadCurrUserInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> user = (Map<String, Object>) request.getSession().getAttribute("user");
        Map<String, Object> res = new HashMap<>();
        try {
            if (user != null) {
                res.put("success", true);
                res.put("type",user.get("type"));
            }
        } catch (Exception e) {
            res.put("failure", e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Boolean logout(HttpServletRequest request) {
        try {
            request.getSession().removeAttribute("user");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
